package cn.slipi.admin.task;

import cn.slipi.admin.common.utils.StrUtils;
import cn.slipi.admin.common.utils.cache.redis.RedisClient;
import cn.slipi.admin.constants.RedisConstants;
import cn.slipi.admin.dao.RequestLogMapper;
import cn.slipi.admin.entity.RequestLog;
import cn.slipi.admin.task.dto.RequestLogDTO;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class RedisSchedule {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisSchedule.class);


    @Autowired
    private RedisClient redisClient;

    @Autowired
    private RequestLogMapper requestLogMapper;


    @Scheduled(fixedDelay = 5000)
    public void cancelAll() {
        LOGGER.info("消费请求日志开始==================");
        int count = 0;
        while (count < 1000) {
            RequestLogDTO requestLogDTO = this.redisClient.rPop(RedisConstants.REQUEST_LOG, RequestLogDTO.class);
            if (requestLogDTO == null) {
                break;
            }
            RequestLog requestLog = new RequestLog();
            requestLog.setAppKey(requestLogDTO.getAppKey());
            requestLog.setApiCode(requestLogDTO.getApiCode());
            requestLog.setHeader(requestLogDTO.getHeader());
            requestLog.setRequest("");
            requestLog.setResponse("");
            requestLog.setStartTimestamp(requestLogDTO.getStartTimestamp());
            requestLog.setEndTimestamp(requestLogDTO.getEndTimestamp());
            requestLog.setContent(JSONObject.toJSONString(requestLogDTO));
            if (StrUtils.isNotBlank(requestLogDTO.getResponse()) && StrUtils.isBlank(requestLogDTO.getException())) {
                requestLog.setSuccess(1);
            } else {
                requestLog.setSuccess(0);
            }
            this.requestLogMapper.insert(requestLog);
            count++;
        }
        LOGGER.info("消费请求日志结束:共处理{}条==================", count);
    }
}
